//
//  MineViewController.m
//  tristana
//
//  Created by 李康 on 2021/1/5.
//  Copyright © 2021 李康. All rights reserved.
//

#import "MineViewController.h"

#import "TSLoginVC.h"
#import "TSToast.h"

#import "ReportVC.h"
#import "AboutVC.h"

#import "UserService.h"
#import "UserBean.h"
#import "TiaoZiListVC.h"
#import "MessageViewController.h"
#import <SDWebImage/SDWebImage.h>
#import "CalculatorVC.h"

@interface MineViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *login;
@property (weak, nonatomic) IBOutlet UIButton *JieTiao;
@property (weak, nonatomic) IBOutlet UIButton *qianTiao;
@property (weak, nonatomic) IBOutlet UIImageView *icon;

@end

@implementation MineViewController


#pragma mark - Public Method

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initAllPropertys];
    [self setupUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryData) name:@"kloginsuccess" object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    
    [self queryData];

}
#pragma mark - Data Query
- (void)queryData {
    if ([UserService isLogin]) {
        UserBean *bean = [UserService getUserBean];
        self.login.text = bean.phone;
        
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSData *imageData = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"kUserIcon_%@",bean.phone]];
                if (imageData) {
                    self.icon.image = [UIImage imageWithData:imageData];;
                }
            });
        });
        
        
//        [self.icon sd_setImageWithURL:nil placeholderImage:[UIImage imageWithData:imageData]];
        
        NSMutableArray *arr1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"recordData1"];
        [self.JieTiao setTitle:[NSString stringWithFormat:@"我的借条(%lu)",(unsigned long)arr1.count] forState:UIControlStateNormal];
        
        NSMutableArray *arr2 = [[NSUserDefaults standardUserDefaults] objectForKey:@"recordData2"];
        [self.qianTiao setTitle:[NSString stringWithFormat:@"我的欠条(%lu)",(unsigned long)arr2.count] forState:UIControlStateNormal];
        
    }else {
        self.login.text = @"立即登录";
        self.icon.image = [UIImage imageNamed:@"mine_user"];
        
        [self.qianTiao setTitle:@"我的借条(0)" forState:UIControlStateNormal];
        [self.JieTiao setTitle:@"我的欠条(0)" forState:UIControlStateNormal];
    }
}
#pragma mark - Notification

#pragma mark - UI
- (void)initAllPropertys {
    self.navigationController.navigationBarHidden = YES;
}

- (void)setupUI {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLogin)];
    self.login.userInteractionEnabled = YES;
    [self.login addGestureRecognizer:tap];
    
    
    
    UITapGestureRecognizer *iconTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(iconTapClick)];
    [self.icon addGestureRecognizer:iconTap];
    self.icon.layer.cornerRadius = 25;
    self.icon.layer.masksToBounds = YES;
    
    if ([UserService isLogin]) {
        
        NSData *imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"kUserIcon"];
        if (imageData) {
            self.icon.image = [UIImage imageWithData:imageData];;
        }
    }
    
    
    
    if ([UserService isLogin]) {
        UserBean *bean = [UserService getUserBean];
        self.login.text = bean.phone;
    }else {
        self.login.text = @"立即登录";
    }
}

- (void)tapLogin {
    if (![UserService isLogin]) {
        [TSLoginVC  showLoginVC];
    }
}

- (void)iconTapClick {
    
    CalculatorVC *vc = [[CalculatorVC alloc] init];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    return;
    
    if (![UserService isLogin]) {
        [TSLoginVC  showLoginVC];
    }else {
        [self selectedImageForIcon];
    }
}
#pragma mark - Delegate

#pragma mark - Private Method

-(void)selectedImageForIcon
{

    UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *actionCamera=[UIAlertAction actionWithTitle:@"打开相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self openSuccWith:@"AV" ];
        
    }];
    
    UIAlertAction *actionPhotoLIbrary=[UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
       [self openSuccWith:@"PH" ];
        
    }];
    
//    UIAlertAction *actionPhotoAlbum=[UIAlertAction actionWithTitle:@"打开图库" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//
//        _imagePicker.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
//        [self presentViewController:_imagePicker animated:YES completion:nil];
//
//    }];
    
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertController addAction:cancelAction];
    [alertController addAction:actionCamera];
    
//    [alertController addAction:actionPhotoAlbum];
    
    [alertController addAction:actionPhotoLIbrary];
    
    
    [self presentViewController:alertController animated:YES completion:nil];

}

- (void)guideUserOpenAuth{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请打开访问权限" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
    UIAlertAction *act = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 引导用户设置
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        }
    }];
    [alertC addAction:alertA];
    [alertC addAction:act];
    [self presentViewController:alertC animated:YES completion:nil];
}

// 打开相机/相册
- (void)openSuccWith:(NSString *)flag{
    
    UIImagePickerController *photoPicker = [UIImagePickerController new];
    photoPicker.delegate = self;
    photoPicker.allowsEditing = NO;
    
    if ([flag isEqualToString:@"AV"]) {
        BOOL useable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];

        if (useable) {
            photoPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }else {
            [self guideUserOpenAuth];
        }
        
    }
    if ([flag isEqualToString:@"PH"]) {
        photoPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    [self presentViewController:photoPicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:@"public.image"]) {
        UIImage * image;
        // 判断，图片是否允许修改
        if ([picker allowsEditing]){
            //获取用户编辑之后的图像
            image = [info objectForKey:UIImagePickerControllerEditedImage];
        } else {
            // 照片的元数据参数
            image = [info objectForKey:UIImagePickerControllerOriginalImage];
        }
        
        // 压缩图片
        UIImage *compressImg = image;//[self compressPictureWith:image];
        self.icon.image = compressImg;
        
         NSData *imagedata = UIImagePNGRepresentation(image);

        [[NSUserDefaults standardUserDefaults] setObject:imagedata forKey:[NSString stringWithFormat:@"kUserIcon_%@",[UserService getUserBean].phone]];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        //        NSLog(@"%@",NSStringFromCGSize(compressImg.size));
        // 用于上传
        NSData *tmpData = UIImageJPEGRepresentation(compressImg, 0.5);
        
    }
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 100)
    {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            switch (buttonIndex)
            {
                case 0:
                    //来源:相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //来源:相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    return;
            }
        }
        else
        {
            if (buttonIndex == 2)
            {
                return;
            }
            else
            {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        //跳转到相机或者相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        imagePickerController.delegate = self;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}
 

 


 
#pragma mark - Overwrite Method

#pragma mark - Event Response

- (IBAction)jietiao:(id)sender {
    if (![UserService isLogin]) {
        [TSLoginVC showLoginVC];
        return;
    }
    TiaoZiListVC *vc = [[TiaoZiListVC alloc] init];
    vc.type = 0;
    vc.fromMine = YES;
    vc.title = @"我的借条";
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
- (IBAction)qiantiao:(id)sender {
    if (![UserService isLogin]) {
        [TSLoginVC showLoginVC];
        return;
    }
    TiaoZiListVC *vc = [[TiaoZiListVC alloc] init];
    vc.type = 1;
    vc.fromMine = YES;
    vc.title = @"我的欠条";
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
- (IBAction)outt:(id)sender {
    if ([UserService isLogin]) {
        [UserService deleteUserBean];
        [TSToast toast: @"退出成功"];
        [self queryData];
    }
}
- (IBAction)shoucang:(id)sender {
    NSLog(@"收藏");
    if ([UserService isLogin]) {
        [TSToast toast: @"当前暂无消息通知"];
    }else {
        [TSLoginVC showLoginVC];
    }
}
- (IBAction)yijian:(id)sender {
    NSLog(@"意见");
    if ([UserService isLogin]) {
        ReportVC *vc = [[ReportVC alloc] init];
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        self.hidesBottomBarWhenPushed = NO;
    }else {
        [TSLoginVC showLoginVC];
    }
}
- (IBAction)guanyu:(id)sender {
    NSLog(@"关于");
    
    AboutVC *vc = [[AboutVC alloc] init];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
}
- (IBAction)qingli:(id)sender {
    NSLog(@"清理");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [TSToast toast:@"清理成功"];
    });
    
}
#pragma mark - Setter

#pragma mark - Getter

@end
